# -*- coding: utf-8 -*-
import json
import logging
# pip install mysql-connector-python
import mysql.connector

logger = logging.getLogger(__name__)

class MysqlTab:
    """ MysqlTab """

    def __init__(self ):
        logger.info(' MysqlTab -init')
        self.conn = mysql.connector.connect(
            user='testfrom',
            password='testfrom',
            host='8.130.66.117',
            database='testfrom'
        )

    def close(self):
        self.conn.close()

    def getLike(self,conditions,column_name):
        size = len(conditions)
        # 构建SQL查询语句
        sql_like = ""
        for i in range(size):
            if len(sql_like) > 0:
                sql_like += " OR "
            sql_like += f"{column_name} LIKE '%{conditions[i]}%' "
        return sql_like

    def getTabs(self,cond):
        # 定义查询条件
        # cond='条件,角色id,用户名称,系统管理员,查询,用户,备注'
        conditions = cond.split(",")
        col_name=self.getLike(conditions,'column_name')
        col_com=self.getLike(conditions,'column_comment')
        tab_name=self.getLike(conditions,'table_name')
        tab_com=self.getLike(conditions,'table_comment')

        tab_sql =f'''
        SELECT  DISTINCT table_name
        from (
        select table_name  from  information_schema.columns where 
        {col_name} OR {col_com}  
        union    
        SELECT table_name
        FROM information_schema.tables
        WHERE {tab_name} OR {tab_com} 
        ) t where t.table_name like '%system_%'
        '''
        # 创建游标对象
        cursor = self.conn.cursor()
        try:
            # 执行SQL查询获取表的注释
            cursor.execute(tab_sql)
            # 获取查询结果
            tables = cursor.fetchall()
            # 输出结果
            # 将表名称存储在数组中
            ret = [table[0] for table in tables]
        finally:
            # 关闭游标和数据库连接
            cursor.close()
        logger.info(ret)
        return ret

#tabs = MysqlTab()
#ret=tabs.getTabs()
#print(ret)
#tabs.close()